<?php
	/* calculator.php
	*   by Allen Wu (103-790-579)
	*   CS 143, Spring 2012
	*   4/6/2012
	********************************************/

	// determines if an expression contains invalid characters
	function isInvalidExpression($expr) {
		return preg_match('/[^\d\.\+\-\*\/\s]/', $expr);
	}

	// adds proper spacing to expression to allow for correct evaluation
	// eg: "1--3+-1" => "1 - - 3 + - 1"
	function padOperators($expr) {
		// make sure every operator has spaces on both sides
		return preg_replace('/(\+|\-|\*|\/)/', ' $1 ', $expr);
	}

	// initialize the output string
	$output = '';

	// if an expression was entered and it's not blank, then attempt to evaluate it
	if (isset($_GET['expr']) && trim($_GET['expr']) !== '') {
		$output = "<h3>Result</h3>\n";
		$expr = $_GET['expr'];

		if (!isInvalidExpression($expr)) {
			// use eval() to calculate the result of the arithmetic expression
			// suppress errors using "@" operator
			@eval('$result = ' . padOperators($expr) . ';');

			// if the value of $result is undefined, that means the eval() failed
			// therefore, the result should be left blank (eg: divide-by-zero)
			if (!isset($result)) {
				$result = '';
			}

			$output .= "{$expr} = {$result}";
		}
		else {
			$output .= "Invalid input expression {$expr}.";
		}
	}

?>
<!DOCTYPE html>
<html>
	<head>
		<title>Calculator</title>
	</head>
	<body>
		<h1>CS 143 Simple PHP Calculator</h1>
		<h2>by Allen Wu, 103-790-579</h2>
		<form method="GET">
			<input id="expr" name="expr" type="text" />
			<input type="submit" value="Calculate" />
		</form>
		<div id="result">
			<?php echo $output; ?>

		</div>
	</body>
</html>